package com.godyao.security.jwt.handler;

import com.godyao.enums.ResultMsg;
import com.godyao.utils.ResponseUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author godyao
 * @date 2022/3/16
 */
@Component
@Slf4j
public class LoginAuthenticationFailureHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        if (e instanceof BadCredentialsException) {
            ResponseUtils.result(httpServletResponse, ResultMsg.builder().code(200).msg("用户名或密码不正确").data(null).build());
        }
        ResponseUtils.result(httpServletResponse, ResultMsg.builder().code(200).msg("登录失败").data(null).build());
    }
}
